package com.weizhi.file.controller.admin;

import com.weizhi.server.dto.FileDto;
import com.weizhi.server.dto.ResponseDto;
import com.weizhi.server.enums.FilePurposeEnum;
import com.weizhi.server.service.FileService;
import lombok.Cleanup;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Arrays;

@RestController
@RequestMapping("/admin/upload")
public class UploadController {

    @Autowired
    private FileService fileService;
    @Autowired
    private Environment env;

    @Value("${staticUrl}")
    private String staticUrl;

    @Value("${rootDir}")
    private String rootDir;

    private final static Logger logger = LoggerFactory.getLogger(UploadController.class);

    @SneakyThrows
    @RequestMapping("/{dir1}/{dir2}")
    public ResponseDto file(@RequestParam MultipartFile file, @PathVariable("dir1") String dir1,
                             @PathVariable("dir2") String dir2, int purpose){
        logger.info("UploadController-image, type={}, name={}", file.getContentType(), file.getOriginalFilename());
        //文件相对目录
        String fileRelativeDir = "static" + File.separator + dir1 + File.separator + dir2 + File.separator;
        String fileDirStr = rootDir + fileRelativeDir;

        //获取文件类型，包含
        String originalFilename = file.getOriginalFilename();
        int splitIndex = originalFilename.lastIndexOf(".");
        String fileName = splitIndex == -1 ? "blob" : originalFilename.substring(0, splitIndex);
        String suffix = originalFilename.substring(splitIndex + 1);

        Long currentTime = System.currentTimeMillis();

        //保存的文件名
        String targetName = fileName + "-" + currentTime + "." + suffix;
        File fileDir = new File(fileDirStr);
        if(!fileDir.exists()) fileDir.mkdirs();
        File target = new File(fileDir, targetName);
        file.transferTo(target);

        //初始化FileDto
        FileDto fileDto = new FileDto();
        fileDto.setName(targetName);
        fileDto.setSuffix(suffix);
        fileDto.setPath(staticUrl + fileRelativeDir + targetName);
        fileDto.setPurpose(purpose);
        fileDto.setSize(Math.toIntExact(file.getSize()));

        logger.info("文件地址={}", fileDto.getPath());
        logger.info("fileDto={}", fileDto);
        //保存到File表
        fileService.save(fileDto);

        return ResponseDto.createBySuccess(fileDto);
    }



    @RequestMapping("/test")
    public String test(HttpServletRequest req){
        String path = "success";
//        path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
//        path = Class.class.getClass().getResource("/").getPath();
        path = env.getProperty("profile");
        return path;
    }

    public static void main(String[] args) {
        String f = "F:\\static\\image\\teacher\\a";
        File file = new File(f, "a.txt");
        if(!file.exists()) file.mkdirs();
    }

}
